//
//  AzirRPCService.swift
//  Center_RPC
//
//  Created by 蒋晨成 on 2021/12/28.
//

import Foundation
import GRPC
import LogMan

public final class AzirRPCService: RPCService {
    private let name: String = "azir"

    let requestQueue: DispatchQueue
    let resultQueue: DispatchQueue
    let context: AzirRPCServiceContextual

    public init(context: AzirRPCServiceContextual, requestQueue: DispatchQueue, resultQueue: DispatchQueue) {
        self.context = context
        self.requestQueue = requestQueue
        self.resultQueue = resultQueue
        super.init(name: Self.name, host: Self.host, port: Self.port, tls: Self.tls)
    }
}

public extension AzirRPCService {
    func callOptions(additionHeader: [(String, String)] = []) -> CallOptions {
        let guid = context.guid
        let sessionID = context.sessionID
        let bundleID = Bundle.main.bundleIdentifier ?? ""
        let version = (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String) ?? ""
        let build = (Bundle.main.infoDictionary?["CFBundleVersion"] as? String) ?? ""
        let language = Bundle.main.preferredLocalizations.first ?? ""
        let regionCode = Locale.current.regionCode ?? ""

        let defaultHeaders = [
            ("X-AZIR-GUID", guid),
            ("X-AZIR-SID", sessionID),
            ("X-AZIR-BID", bundleID),
            ("X-AZIR-VERSION", version),
            ("X-AZIR-BUILD", build),
            ("X-AZIR-LANGUAGE", language),
            ("X-AZIR-REGIONCODE", regionCode),
        ]

        let allHeaders = defaultHeaders + additionHeader
        return CallOptions(
            customMetadata: .init(allHeaders),
            timeLimit: .timeout(.seconds(10)),
//             cacheable: true // 加了就有bug，不知为啥
            logger: logger
        )
    }
}

private extension AzirRPCService {
    #if DEBUG
        static let host: String = "172.16.201.118"
    #else
        static let host: String = "djangoc.com"
    #endif

    static let port: Int = 443
    static let name: String = "azir"
    static let tls: Bool = false
}
